﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Reflection;
using Dal.Entities;
using Framework.Data;
using System.Web.Security;
using System.Text;

namespace Web.Controllers
{
    public class Common
    {
        public static string GetRegionName(int regionID)
        {
            var region = RepositoryFactory.GetRepository().GetByKey<Region>(regionID);
            if (region != null)
            {
                return region.BriefName;
            }
            return string.Empty;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="alert"></param>
        public static void Alert(string alert)
        {
            HttpContext.Current.Response.Write("<script>alert('" + alert + "')</script>");
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="alert"></param>
        /// <param name="redirectUrl"></param>
        public static void AlertRedirect(string alert, string redirectUrl)
        {
            HttpContext.Current.Response.Write("<script>alert('" + alert + "')</script>");
            HttpContext.Current.Response.Write("<script>location.href = '" + redirectUrl + "' ;</script>");
            HttpContext.Current.Response.End();
        }
        /// <summary>
        /// 获取用户名
        /// </summary>
        /// <returns></returns>
        public static string GetUserName()
        {
            return GetTicket().Name.Split('|')[0];
        }

        /// <summary>
        /// 获取用户名ID
        /// </summary>
        /// <returns></returns>
        public static int GetUserID()
        {
            return int.Parse(GetTicket().Name.Split('|')[1]);
        }

        /// <summary>
        /// 获取角色
        /// </summary>
        /// <returns></returns>
        public static int GetUserRole()
        {
            return int.Parse(GetTicket().Name.Split('|')[2]);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public static bool Admin()
        {
            return GetUserRole() >= 1;
        }


        /// <summary>
        /// 获取角色
        /// </summary>
        /// <returns></returns>
        public static int DocType()
        {
            return int.Parse(GetTicket().UserData);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public static FormsAuthenticationTicket GetTicket()
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
            FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
            return ticket;
        }



        /// <summary>
        /// 
        /// </summary>
        /// <param name="userID"></param>
        /// <returns></returns>
        public static string GetUserName(int userID)
        {
            var user = RepositoryFactory.GetRepository().GetByKey<User>(userID);
            if (user != null)
            {
                return user.UserName;
            }
            return string.Empty;
        }

        public static string GetQuestionDesc(int docid, string field, int type, string desc)
        {
            //if (Common.Admin())
            //{
            string tmp = string.Empty;
            var allquestion = RepositoryFactory.GetRepository().Get<DocQuestion>(i => i.DocID == docid && i.FieldName == field && i.Type == type);
            string strOnclick = "question('" + field + "'," + type + ",'" + desc + "');";
            if (allquestion == null || allquestion.Count == 0)//黑色无质疑
            {
                tmp += "<a href=\"#\" class=\"table_comment0\" onclick=\"" + strOnclick + "\" title=\"添加质疑\">comment</a>";
            }
            else
            {
                if (allquestion.Where(i => i.Status == 0).Count() > 0)//red
                {
                    tmp += "<a href=\"#\" class=\"table_comment\" onclick=\"" + strOnclick + "\" title=\"存在未关闭质疑\">comment</a>";
                }
                if (allquestion.Where(i => i.Status == 1).Count() > 0)
                {
                    tmp += "<a href=\"#\" class=\"table_comment1\" onclick=\"" + strOnclick + "\" title=\"存在已关闭质疑\">comment</a>";
                }
            }
            return tmp;
            //}
            //return string.Empty;
        }

        /// <summary>
        /// 判断 doccommon  doc1 doc2 doc3 doc4
        /// </summary>
        /// <param name="docid"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public static bool HasQuestion(int docid, int type)
        {
            var question = RepositoryFactory.GetRepository().First<DocQuestion>(i => i.DocID == docid && i.Type == type);
            if (question != null)
            {
                return true;
            }
            return false;
        }

        public static void UpdateModifyStatus(int docId)
        {
            var rep = RepositoryFactory.GetRepository();
            if (rep.First<DocQuestion>(i => i.DocID == docId && i.Status == 0) != null)
            {
                var doc = new Doc { DocID = docId, StatusModify = -1 };
                rep.Attach(doc);
                doc.StatusModify = 1;
                doc.TimeUpdate = DateTime.Now;
                rep.Save();
            }

        }


        public static void SetComplete(int docid)
        {
            var resp = RepositoryFactory.GetRepository();

            var doc = resp.GetByKey<Doc>(docid);
            var doc0 = resp.GetByKey<DocCommon>(docid);
            var doc1 = resp.GetByKey<Doc1>(docid);
            var doc2 = resp.GetByKey<Doc2>(docid);
            var doc3 = resp.GetByKey<Doc3>(docid);
            resp.Attach(doc);
            if (doc.DocType == 2)
            {
                var doc4 = resp.GetByKey<Doc4>(docid);
                if (doc0.StatusComplete == 1 && doc1.StatusComplete == 1 && doc2.StatusComplete == 1 && doc3.StatusComplete == 1 && doc4.StatusComplete == 1)
                {
                    doc.StatusComplete = 1;
                }
                else
                {
                    doc.StatusComplete = 0;
                }
            }
            if (doc.DocType == 1)
            {
                if (doc0.StatusComplete == 1 && doc1.StatusComplete == 1 && doc2.StatusComplete == 1 && doc3.StatusComplete == 1)
                {
                    doc.StatusComplete = 1;
                }
                else
                {
                    doc.StatusComplete = 0;
                }
            }
            resp.Save();
        }

        public static void SetAudit(int docid)
        {
            var resp = RepositoryFactory.GetRepository();

            var doc = resp.GetByKey<Doc>(docid);
            var doc0 = resp.GetByKey<DocCommon>(docid);
            var doc1 = resp.GetByKey<Doc1>(docid);
            var doc2 = resp.GetByKey<Doc2>(docid);
            var doc3 = resp.GetByKey<Doc3>(docid);
            resp.Attach(doc);
            if (doc.DocType == 2)
            {
                var doc4 = resp.GetByKey<Doc4>(docid);
                if (doc0.StatusAudit >= 1 && doc1.StatusAudit >= 1 && doc2.StatusAudit >= 1 && doc3.StatusAudit >= 1 && doc4.StatusAudit >= 1)
                {
                    doc.StatusAudit = 1;
                }
                else
                {
                    doc.StatusAudit = 0;
                }

            }
            if (doc.DocType == 1)
            {
                if (doc0.StatusAudit >= 1 && doc1.StatusAudit >= 1 && doc2.StatusAudit >= 1 && doc3.StatusAudit >= 1)
                {
                    doc.StatusAudit = 1;
                }
                else
                {
                    doc.StatusAudit = 0;
                }
            }
            doc.TimeAudit = DateTime.Now;
            doc.AuditorID = Common.GetUserID();
            resp.Save();
        }

        public static void UpdateQuestionStatus(int docid)
        {
            var resp = RepositoryFactory.GetRepository();
            if (resp.Count<DocQuestion>(i => i.DocID == docid && i.Status == 0) > 0)//存在质疑
            {
                resp.AttachThenSaveChange(new Doc { DocID = docid, StatusQuestion = -1 }, i => i.StatusQuestion = 1);
            }
            else if (resp.Count<DocQuestion>(i => i.DocID == docid && i.Status == 1) > 0)//已关闭质疑
            {
                resp.AttachThenSaveChange(new Doc { DocID = docid, StatusQuestion = -1, StatusModify = -1 }, i => { i.StatusQuestion = 2; i.StatusModify = 0; });
            }
            else//不存在质疑 更新质疑状态 更新质疑响应状态
            {
                resp.AttachThenSaveChange(new Doc { DocID = docid, StatusQuestion = -1, StatusModify = -1 }, i => { i.StatusQuestion = 0; i.StatusModify = 0; });
            }
        }

        public static string GetStatusString(int docID, int type)
        {
            var resp = RepositoryFactory.GetRepository();
            var doc = resp.GetByKey<Doc>(docID);
            int question = resp.First<DocQuestion>(i => i.DocID == docID && i.Type == type && i.Status == 0) == null ? 0 : 1;
            StringBuilder sb = new StringBuilder();
            if (type == 0)
            {
                var model = resp.GetByKey<DocCommon>(docID);
                if (model != null)
                {
                    RenderStatus(sb, model.StatusComplete, model.StatusAudit, question);
                }
            }
            else if (type == 1)
            {
                var model = resp.GetByKey<Doc1>(docID);
                if (model != null)
                {
                    RenderStatus(sb, model.StatusComplete, model.StatusAudit, question);
                }
            }
            else if (type == 2)
            {
                var model = resp.GetByKey<Doc2>(docID);
                if (model != null)
                {
                    RenderStatus(sb, model.StatusComplete, model.StatusAudit, question);
                }
            }
            else if (type == 3)
            {
                var model = resp.GetByKey<Doc3>(docID);
                if (model != null)
                {
                    RenderStatus(sb, model.StatusComplete, model.StatusAudit, question);
                }
            }
            else if (type == 4)
            {
                var model = resp.GetByKey<Doc4>(docID);
                if (model != null)
                {
                    RenderStatus(sb, model.StatusComplete, model.StatusAudit, question);
                }
            }
            return sb.ToString();
        }
        private static void RenderStatus(StringBuilder sb, int complete, int audit, int question)
        {
            if (complete == 1)
            {
                sb.Append("<a href=\"#\" class=\"iconok\" title=\"已完成\" >ok</a>");
            }
            else
            {
                sb.Append("<a href=\"#\" class=\"iconnotice\" title=\"未完成\" >ok</a>");
            }
            if (audit >= 1)
            {
                sb.Append("<a href=\"#\" class=\"iconpassaudit\" title=\"已审核\" >ok</a>");
            }
            else
            {
                sb.Append("<a href=\"#\" class=\"iconcha\" title=\"未审核\" >ok</a>");
            }
            if (question >= 1)
            {
                sb.Append("<a href=\"#\" class=\"iconwenhao\" title=\"有质疑\" >ok</a>");
            }
        }

        public static string GetDaysDescription(string input)
        {
            if (!string.IsNullOrEmpty(input))
            {
                StringBuilder sb = new StringBuilder();
                string[] array = input.Split(',');
                for (int i = 0; i < array.Length; i++)
                {
                    sb.Append("第" + (i + 1) + "天:" + array[i] + "|");
                }
                return sb.ToString();
            }
            return string.Empty;
        }
    }
    /// <summary>
    /// 自定义认证
    /// </summary>
    public class MyAuthAttribute : AuthorizeAttribute
    {
        /// <summary>
        /// 
        /// </summary>
        public int Role { get; set; }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="httpContext"></param>
        /// <returns></returns>
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (Role <= Common.GetUserRole())
                return true;
            else
                return false;
        }
    }

    /// <summary>
    /// 外部决定action
    /// </summary>
    public class HttpParamActionAttribute : ActionNameSelectorAttribute
    {
        /// <summary>
        /// 重写 IsValid
        /// </summary>
        /// <param name="controllerContext"></param>
        /// <param name="actionName"></param>
        /// <param name="methodInfo"></param>
        /// <returns></returns>
        public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)
        {
            if (actionName.Equals(methodInfo.Name, StringComparison.InvariantCultureIgnoreCase))
                return true;

            if (!actionName.Equals("Action", StringComparison.InvariantCultureIgnoreCase))
                return false;

            return controllerContext.RequestContext.HttpContext.Request[methodInfo.Name] != null;
        }
    }
}
